<template>
  <div class="content">
    <div class="ui-container" v-if="record.isNewRecord || record.ctitle">
      <!-- 基本信息START -->
      <div>
        <a-row>
          <a-col
            :xs="{ span: 24, order: 2 }"
            :sm="{ span: 24, order: 2 }"
            :md="{ span: 15, order: 1 }"
            :lg="{ span: 15, order: 1 }"
            :xl="{ span: 15, order: 1 }"
            :xxl="{ span: 15, order: 1 }"
          >
            <div v-if="editQuesContent">
              <a-form :model="record">
                <a-form-item>
                  <a-input
                    v-model:value="record.ctitle"
                    label="标题"
                    placeholder="标题"
                    :rules="[{ required: true, message: '标题不能为空!' }]"
                  >
                    <template #prefix></template>
                  </a-input>
                </a-form-item>
                <a-form-item>
                  <WangEditor
                    v-model:value="record.ccontent"
                    :bizKey="record.id"
                    :bizType="'quesLibInfo_ccontent'"
                    :height="450"
                    :rules="[{ required: true, message: '内容不能为空' }]"
                  />
                </a-form-item>
              </a-form>
            </div>
            <div v-else>
              <a-descriptions
                :labelStyle="{ 'font-size': '28px !important' }"
                :column="{ xs: 1, sm: 2, md: 2, lg: 3, xl: 3, xxl: 3 }"
              >
                <template #title>
                  <div class="font-bold text-[28px]">{{ record.ctitle }}</div>
                </template>
                <template #extra>
                  <a-space v-if="!entiInfo">
                    <a-button type="primary" @click="edit = !edit"><edit-outlined />修改</a-button>
                    <a-button v-if="record.milestone != '6'" @click="deleteInfo"
                      ><delete-outlined />删除</a-button
                    >
                    <!--  <a-button
                      @click="
                        async () => {
                          await closeCurrentTabPage();
                        }
                      "
                      >关闭</a-button
                    > -->
                  </a-space>
                </template>
                <a-descriptions-item label="状态" :labelStyle="labelStyle">
                  <DictLabel dictType="quesLib_ques_step" :dictValue="record.step" />
                  &nbsp;&nbsp;&nbsp;&nbsp;
                  <DictLabel dictType="quesLib_milestone" :dictValue="record.milestone" />
                </a-descriptions-item>
                <a-descriptions-item label="创建人" :labelStyle="labelStyle">{{
                  record.creator?.userName
                }}</a-descriptions-item>
                <a-descriptions-item label="创建时间" :labelStyle="labelStyle">{{
                  record.createDate
                }}</a-descriptions-item>
              </a-descriptions>
              <a-divider style="border-color: #cccccc,margin-top: 18px !important" />
              <div class="ccontent" v-html="record.ccontent"></div>
            </div>
          </a-col>
          <a-col
            :xs="{ span: 24, order: 1 }"
            :sm="{ span: 24, order: 1 }"
            :md="{ span: 8, order: 2, offset: 1 }"
            :lg="{ span: 8, order: 2, offset: 1 }"
            :xl="{ span: 8, order: 2, offset: 1 }"
            :xxl="{ span: 8, order: 2, offset: 1 }"
          >
            <div class="tool">
              <div v-if="showKeep">
                <a-space>
                  <a-button type="primary" @click="handleSubmit(1)">暂存</a-button>
                  <a-button type="primary" @click="handleSubmit(2)">发布</a-button>
                  <a-button
                    @click="
                      async () => {
                        await closeCurrentTabPage();
                      }
                    "
                    >关闭</a-button
                  >
                </a-space>
              </div>
              <div v-if="edit">
                <a-space>
                  <a-button type="primary" @click="keep">保存</a-button>
                  <a-button @click="edit = !edit">取消</a-button>
                </a-space>
              </div>
            </div>
            <div>
              <BasicForm @register="registerForm">
                <template #joinPrj>
                  <a-button type="primary" @click="handleJoinPrj">关联项目</a-button>
                  <ListSelect
                    ref="prjSelRef"
                    @select="prjSelect"
                    selectType="PLMPrjSelect"
                    v-show="false"
                  />
                </template>
                <template #infoFileUpload>
                  <BasicUpload
                    v-model:value="record.dataMap"
                    :bizKey="record.id"
                    :bizType="'queslibInfo_file'"
                    :uploadType="'all'"
                    :loadTime="record.__t"
                    :showPreview="true"
                    :emptyHidePreview="true"
                    @change="handleUploadChange"
                    ref="infoFileUploadRef"
                  />
                </template>
                <!-- <template #formFooter>
                  <a-button type="primary" @click="handleJoinPrj">关联项目</a-button>
                </template> -->
              </BasicForm>
            </div>
          </a-col>
        </a-row>
      </div>
      <!-- 基本信息END -->
      <!-- 方案START -->
      <a-divider
        v-if="record.plan"
        orientation="left"
        class="span-line"
        ref="planRef"
        orientationMargin="0"
      >
        <div style="display: flex">
          <img src="../../assets/svg/queslib/plan.svg" style="display: inline-block" />
          <span>方案信息</span>
        </div>
      </a-divider>
      <div v-if="record.plan">
        <a-row>
          <a-col
            :xs="{ span: 24, order: 1 }"
            :sm="{ span: 24, order: 1 }"
            :md="{ span: 15, order: 1 }"
            :lg="{ span: 15, order: 1 }"
            :xl="{ span: 15, order: 1 }"
            :xxl="{ span: 15, order: 1 }"
            class="plan-content"
          >
            <a-descriptions :column="{ xs: 1, sm: 2, md: 2, lg: 3, xl: 3, xxl: 3 }">
              <a-descriptions-item label="状态" :labelStyle="labelStyle">
                <DictLabel dictType="quesLib_plan_status" :dictValue="record.plan.cstatus"
              /></a-descriptions-item>
              <a-descriptions-item label="创建人" :labelStyle="labelStyle">{{
                record.plan.creator?.userName
              }}</a-descriptions-item>
              <a-descriptions-item label="时间" :labelStyle="labelStyle">{{
                record.plan.createDate
              }}</a-descriptions-item>
              <a-descriptions-item label="确认人" :labelStyle="labelStyle">{{
                record.plan.auditor?.userName
              }}</a-descriptions-item>
              <a-descriptions-item label="确认时间" :labelStyle="labelStyle">{{
                record.plan.auditDate
              }}</a-descriptions-item>
              <a-descriptions-item label="意见" :labelStyle="labelStyle">{{
                record.plan.remarks
              }}</a-descriptions-item>
            </a-descriptions>
            <a-divider style="border-color: #cccccc" />
            <div class="ccontent" v-html="record.plan.ccontent"></div>
          </a-col>
          <a-col
            :xs="{ span: 24, order: 2 }"
            :sm="{ span: 24, order: 2 }"
            :md="{ span: 8, order: 2, offset: 1 }"
            :lg="{ span: 8, order: 2, offset: 1 }"
            :xl="{ span: 8, order: 2, offset: 1 }"
            :xxl="{ span: 8, order: 2, offset: 1 }"
          >
            <BasicForm @register="registerForm2" />
            <div
              style="margin-top: 20px; display: flex; justify-content: center; align-items: center"
            >
              <a-space>
                <a-button
                  class="!bg-color-[#4263ec]"
                  v-if="record.editPlan"
                  @click="openDrawer(true, { quesId: quesId, id: record.plan.id, openType: 1 })"
                  ><edit-outlined />修改</a-button
                >
                <a-button
                  class="!bg-color-[#98ff4a]"
                  v-if="record.plan.cstatus === '1' && record.managed"
                  @click="handlePlanSubmit()"
                  ><check-outlined />提交</a-button
                >
                <a-button
                  type=""
                  @click="
                    openPlanHistoryDrawer(true, { quesId: quesId, id: record.plan.id, openType: 2 })
                  "
                  ><eye-two-tone />历史</a-button
                >
              </a-space>
            </div>
          </a-col>
        </a-row>
      </div>
      <!-- 方案END -->
      <!-- 结果START -->
      <a-divider
        v-if="record.res"
        orientation="left"
        class="span-line"
        ref="resRef"
        orientationMargin="0"
        style="display: flex"
      >
        <img src="../../assets/svg/queslib/result.svg" style="display: inline-block" />
        <span>结果信息</span>
      </a-divider>
      <div v-if="record.res">
        <a-row>
          <a-col
            :xs="{ span: 24, order: 1 }"
            :sm="{ span: 24, order: 1 }"
            :md="{ span: 15, order: 1 }"
            :lg="{ span: 15, order: 1 }"
            :xl="{ span: 15, order: 1 }"
            :xxl="{ span: 15, order: 1 }"
            class="res-content"
          >
            <a-descriptions :column="{ xs: 1, sm: 2, md: 2, lg: 3, xl: 3, xxl: 3 }">
              <a-descriptions-item label="状态" :labelStyle="labelStyle">
                <DictLabel dictType="quesLib_plan_status" :dictValue="record.res.resStatus"
              /></a-descriptions-item>
              <a-descriptions-item label="创建人" :labelStyle="labelStyle">{{
                record.res.creator?.userName
              }}</a-descriptions-item>
              <a-descriptions-item label="时间" :labelStyle="labelStyle">{{
                record.res.createDate
              }}</a-descriptions-item>
              <a-descriptions-item label="确认人" :labelStyle="labelStyle">{{
                record.res.auditor?.userName
              }}</a-descriptions-item>
              <a-descriptions-item label="确认时间" :labelStyle="labelStyle">{{
                record.res.auditDate
              }}</a-descriptions-item>
              <a-descriptions-item label="意见" :labelStyle="labelStyle">{{
                record.res.remarks
              }}</a-descriptions-item>
            </a-descriptions>
            <a-divider style="border-color: #cccccc" />
            <div class="ccontent" v-html="record.res.ccontent"></div>
          </a-col>
          <a-col
            :xs="{ span: 24, order: 2 }"
            :sm="{ span: 24, order: 2 }"
            :md="{ span: 8, order: 2, offset: 1 }"
            :lg="{ span: 8, order: 2, offset: 1 }"
            :xl="{ span: 8, order: 2, offset: 1 }"
            :xxl="{ span: 8, order: 2, offset: 1 }"
          >
            <BasicForm @register="registerForm3" />
            <div
              style="margin-top: 20px; display: flex; justify-content: center; align-items: center"
              ><a-space>
                <a-button
                  class="!bg-color-[#4263ec]"
                  v-if="record.editRes"
                  @click="openDrawer3(true, { quesId: quesId, id: record.res.id, openType: 1 })"
                  ><edit-outlined />修改</a-button
                >
                <a-button
                  class="!bg-color-[#98ff4a]"
                  v-if="record.res.resStatus === '1'"
                  @click="handleResSubmit"
                  ><check-outlined />提交</a-button
                >
                <a-button
                  @click="
                    openResHistoryDrawer(true, { quesId: quesId, id: record.res.id, openType: 2 })
                  "
                  ><eye-two-tone />历史</a-button
                >
              </a-space>
            </div>
          </a-col>
        </a-row>
      </div>
      <!-- 结果END -->
      <!-- 日志START -->
      <div v-if="record.log">
        <a-row>
          <a-col :span="15">
            <p style="text-align: right; position: relative; top: 30px; z-index: 999">
              <span
                @click="oplog"
                style="font-weight: bold; color: #005980; background-color: #fff"
              >
                全部操作日志 <span v-if="iconFalg"><down-outlined /></span>
                <span v-if="!iconFalg"><up-outlined /></span>
              </span>
            </p>
            <a-timeline v-if="iconFalg" style="margin-left: 50px">
              <a-timeline-item>
                <template #dot
                  ><span style="font-weight: bold"> {{ record.log.createDate }}</span></template
                >
                <div class="d-f" style="display: flex; margin-left: 50px">
                  <div
                    style="margin: 0 5px"
                    v-html="
                      `【<b>${record.log.creator.userName}】</b>&nbsp;&nbsp;${record.log.caction} `
                    "
                  ></div>
                  <div style="margin: 0 10px"> {{ getAgoAt(record.log.createDate) }} </div>
                </div>
              </a-timeline-item>
            </a-timeline>

            <a-timeline v-if="!iconFalg" style="margin-left: 50px">
              <a-timeline-item v-for="(item, index) in logList" :key="index">
                <template #dot
                  ><span style="font-weight: bold"> {{ item.createDate }}</span></template
                >
                <div
                  style="margin-left: 50px"
                  v-html="
                    `【<b>${item.creator.userName}】</b>&nbsp;&nbsp;${item.caction}   ${getAgoAt(
                      item.createDate,
                    )}`
                  "
                ></div>
              </a-timeline-item>
            </a-timeline>
          </a-col>
          <a-col :span="8" :offset="1" />
        </a-row>
      </div>
      <!-- 日志END -->
      <!-- 操作START -->
      <div class="steptool">
        <template v-if="record.step !== '3'">
          <div v-if="record.addPlan">
            <a-button type="default" size="large" @click="submitPlan" style="border-radius: 12px">
              <template #icon><plus-circle-outlined /></template>
              <span>方案制定</span>
            </a-button>
          </div>
          <template v-if="record.conFirmAndBack">
            <div>
              <a-button type="primary" size="large" style="border-radius: 12px" @click="planOpe(4)">
                <template #icon><check-circle-outlined /></template>
                <span>方案确认</span>
              </a-button>
            </div>
            <div>
              <a-button
                type="primary"
                size="large"
                danger
                style="border-radius: 12px"
                @click="planOpe(3)"
              >
                <template #icon><close-circle-outlined /></template>
                <span>方案打回</span>
              </a-button>
            </div>
          </template>
          <div v-if="record.addRes">
            <a-button type="default" size="large" @click="submitRes" style="border-radius: 12px">
              <template #icon><plus-circle-outlined /></template>
              <span>提交结果</span>
            </a-button>
          </div>
          <template v-if="record.conFirmAndBackRes">
            <div>
              <a-button type="primary" size="large" style="border-radius: 12px" @click="resOpe(4)">
                <template #icon><check-circle-outlined /></template>
                <span>结果确认</span>
              </a-button>
            </div>
            <div>
              <a-button
                type="primary"
                size="large"
                danger
                style="border-radius: 12px"
                @click="resOpe(3)"
              >
                <template #icon><close-circle-outlined /></template>
                <span>结果打回</span>
              </a-button>
            </div>
          </template>
        </template>
        <div v-if="record.plan">
          <a-button size="large" @click="toPlanView" style="border-radius: 12px">
            <template #icon><eye-two-tone /></template>
            <span>查看方案</span>
          </a-button>
        </div>
        <div v-if="record.res">
          <a-button size="large" @click="toResView" style="border-radius: 12px">
            <template #icon><eye-two-tone /></template>
            <span>查看结果</span>
          </a-button>
        </div>
      </div>
      <!-- 操作END -->
    </div>
    <InputFormTabs @register="registerDrawer2" @success="handleSuccess" />
    <InputFormTabs3 @register="registerDrawer3" @success="handleSuccess" />
    <PlanHistoryForm @register="registerPlanHistoryDrawer" @success="handleSuccess" />
    <ResHistoryForm @register="registerResHistoryDrawer" @success="handleSuccess" />
    <ConfirmFormTabs @register="registerConfirmDrawer" @success="handleSuccess" />
    <!-- <BasicModal @register="registerPrjDodal"> <ListSelect /></BasicModal> -->
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsQuesLibForm',
  });
</script>
<script lang="ts" setup>
  import { Ref, defineComponent, onMounted, ref, unref, computed } from 'vue';
  import { BasicForm, useForm, FormSchema, FieldMapToTime } from '/@/components/Form/index';
  import { formSet } from '/@/api/test/testData';
  import { formSchemas } from '/@/utils/custom';
  import {
    QueslibInfo,
    queslibInfoForm,
    queslibInfoSave,
    queslibInfoDelete,
    queslibInfoFieldSave,
    saveContent,
  } from '/@/api/quesLib/info/queslibInfo';
  import { QueslibLog, queslibLogSave, queslibLogListData } from '/@/api/quesLib/log/queslibLog';
  import { queslibPlanConfirm } from '/@/api/quesLib/plan/queslibPlan';
  import { queslibResConfirm } from '/@/api/quesLib/res/queslibRes';
  import { useRouter } from 'vue-router';
  import { WangEditor } from '/@/components/WangEditor';
  import { DictLabel } from '/@/components/Dict';
  import { DeleteOutlined } from '@ant-design/icons-vue';
  import { EditOutlined } from '@ant-design/icons-vue';
  import {
    PlusCircleOutlined,
    CheckCircleOutlined,
    CloseCircleOutlined,
    DownOutlined,
    UpOutlined,
    EyeTwoTone,
    CheckOutlined,
  } from '@ant-design/icons-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import InputFormTabs from './plan/formTabs.vue';
  import PlanHistoryForm from './plan/historyForm.vue';
  import ResHistoryForm from './res/historyForm.vue';
  import InputFormTabs3 from './res/formTabs.vue';
  import ConfirmFormTabs from './confirm/formTabs.vue';
  import { useDrawer } from '/@/components/Drawer';
  import { getAgoAt } from '/@/utils/dateUtil';
  import { useDebounceFn } from '@vueuse/core';
  import { useUserStore } from '/@/store/modules/user';
  import { useDict } from '/@/components/Dict/src/useDict';
  import { useTabs } from '/@/hooks/web/useTabs';
  import { ListSelect } from '/@/components/ListSelect';
  import { plmPrjKindInfoListData } from '/@/api/quesLib/prj/plmPrjInfo';
  import { BasicUpload } from '/@/components/Upload';
  const { initDict } = useDict();
  const { closeCurrent, refreshPage } = useTabs();
  const [registerDrawer2, { openDrawer }] = useDrawer();
  const [registerDrawer3, { openDrawer: openDrawer3 }] = useDrawer();
  const [registerPlanHistoryDrawer, { openDrawer: openPlanHistoryDrawer }] = useDrawer();
  const [registerResHistoryDrawer, { openDrawer: openResHistoryDrawer }] = useDrawer();
  const [registerConfirmDrawer, { openDrawer: openConfirmDrawer }] = useDrawer();

  const [registerForm, { setProps, validate, setFieldsValue, getFieldsValue }] = useForm();
  const [registerForm2, { setProps: setProps2, setFieldsValue: setFieldsValue2 }] = useForm();
  const [registerForm3, { setProps: setProps3, setFieldsValue: setFieldsValue3 }] = useForm();
  const { currentRoute } = useRouter();
  const route = unref(currentRoute);
  const { showMessage } = useMessage();
  const formConfig = ref<any>({});
  const record = ref<QueslibInfo>({} as QueslibInfo);
  const showForm = ref(true);
  let iconFalg = ref(true);
  let logList = ref<any>([]);

  const edit = ref(false);
  const planRef = ref<any>(null);
  const resRef = ref<any>(null);
  const userInfo = useUserStore().getUserInfo;
  const fieldMapToTime: FieldMapToTime = [['dateRange', ['beginDate', 'endDate']]];
  const prjSelRef = ref<any>(null);
  const infoFileUploadRef = ref<any>(null);

  // 是否创建人
  const created = computed(
    () => userInfo.userCode == 'system' || record.value.createBy == userInfo.userCode,
  );

  // 是否可以修改标题
  const editQuesContent = computed(() => showForm.value || edit.value || record.value.step === '1');
  const showKeep = computed(() => record.value.step === '1' || !record.value.step);
  const quesId = computed(() => route.query.quesId);
  const entiInfo = computed(() => !created.value || record.value.step === '3');

  const labelStyle = { 'font-weight': 'bold', 'font-size': '14px', color: '#606266' };

  function getProperty(obj: Ref<any>, str: string) {
    str = str.replace(/\[(\w+)\]/g, '.$1'); // 处理数组下标
    let arr = str.split('.');
    let value = { ...obj.value };
    for (let i in arr) {
      value = value[arr[i]] || '';
    }
    return value;
  }

  const closeCurrentTabPage = async () => {
    await closeCurrent();
  };

  /**
   * 单字段保存+操作日志
   */
  const saveFilledData = async (schema, { validate }, formModel, obj) => {
    if (
      !record.value.isNewRecord &&
      record.value.step !== '1' &&
      created &&
      schema.component !== 'Upload' &&
      record.value.step !== '3'
    ) {
      try {
        await validate(); // 验证表单，并返回数据
        let oldValue = getProperty(record, schema.field);
        let newValue: any = formModel[schema.field];
        if (schema.component === 'TreeSelect' || schema.component === 'ListSelect') {
          oldValue = getProperty(record, schema.fieldLabel);
          newValue = formModel[schema.fieldLabel];
        } else if (schema.component === 'RangePicker') {
          const oldDateRange = getProperty(record, schema.field);
          if (oldDateRange) {
            oldValue = oldDateRange[0]
              ? oldDateRange[0]
              : '空' + '-' + oldDateRange[1]
              ? oldDateRange[1]
              : '空';
            if (oldValue === '空-空') {
              oldValue = '';
            }
          }
          newValue = formModel[schema.field][0] + '-' + formModel[schema.field][1];
        }
        const log = {
          quesId: record.value.id,
          fieldName: schema.label,
          oldValue,
          newValue,
          component: schema.component,
          dictType: obj.dictType,
          logType: oldValue ? '1' : '0',
        } as QueslibLog;
        let params = {
          id: record.value.id,
          isNewRecord: record.value.isNewRecord,
        };
        const submitData = {} as QueslibInfo;
        if (schema.component === 'RangePicker' && fieldMapToTime) {
          for (let i = 0; i < fieldMapToTime.length; i++) {
            if (fieldMapToTime[i][0] === schema.field) {
              if (formModel[schema.field]) {
                if (formModel[schema.field][0]) {
                  submitData[fieldMapToTime[i][1][0]] = formModel[schema.field][0];
                }
                if (formModel[schema.field][1]) {
                  submitData[fieldMapToTime[i][1][1]] = formModel[schema.field][1];
                }
              }
            }
          }
        } else {
          submitData[schema.field] = formModel[schema.field];
        }
        queslibInfoFieldSave(params, { ...formModel, ...submitData }).then(() => {
          loadInfoForm();
        });
        if (!schema.field.startsWith('defMap')) {
          queslibLogSave({}, log).then((res) => {
            record.value.log = res.data;
          });
        }
      } catch (error: any) {
        if (error) {
          console.log(error);
        }
      }
    }
  };
  // 保存附件
  const handleUploadChange = (fileList) => {
    if (
      !record.value.isNewRecord &&
      record.value.step !== '1' &&
      created &&
      record.value.step !== '3'
    ) {
      if (fileList.queslibInfo_file || fileList.queslibInfo_file__del) {
        debounceFileSave({ dataMap: { ...fileList } });
      }
    }
  };

  const saveFileData = async (data) => {
    console.log('handleUploadChange', data, record.value.dataMap);
    if (!record.value.id) {
      return;
    }
    let params = {
      id: record.value.id,
      isNewRecord: record.value.isNewRecord,
    };
    await queslibInfoFieldSave(params, data);
  };
  const debounceSave = useDebounceFn(saveFilledData, 1000);
  const debounceFileSave = useDebounceFn(saveFileData, 3000);

  onMounted(async () => {
    // 加字典
    await initDict([
      'quesLib_ques_step',
      'quesLib_ques_type',
      'quesLib_priority_level',
      'quesLib_plan_status',
    ]);
    await loadInfoForm();
    if (record.value.plan) {
      // 方案===========
      loadPlanForm();
      // setFieldsValue2(record.value.plan);
    }
    if (record.value.res) {
      // 结果===========
      loadResForm();
      // setFieldsValue3(record.value.res);
    }
  });
  async function handleSuccess() {
    refreshPage();
  }

  async function oplog() {
    if (iconFalg.value) {
      const data = await queslibLogListData({ quesId: record.value.id });
      logList.value = data.list;
    }
    iconFalg.value = !iconFalg.value;
  }

  const handleSubmit = async (ope) => {
    try {
      const data = await validate();

      let params = {
        id: record.value.id,
        isNewRecord: record.value.isNewRecord,
      };
      let submitData = {
        ctitle: record.value.ctitle,
        ccontent: record.value.ccontent,
        ...data,
        ope,
      };
      const res = await queslibInfoSave(params, submitData);
      showMessage(res.message);
      record.value = res.data;
      record.value.isNewRecord = false;
      await closeCurrentTabPage();
      // await go('/quesLib/index');
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage('您填写的信息有误，请根据提示修正。');
      }
      console.log('error', error);
    }
  };
  function submitPlan() {
    openDrawer(true, { quesId: record.value.id, openType: 1 });
  }

  function submitRes() {
    openDrawer3(true, { quesId: record.value.id, openType: 1 });
  }

  const keep = async () => {
    let params = {
      id: record.value.id,
      ctitle: record.value.ctitle,
      ccontent: record.value.ccontent,
    } as QueslibInfo;
    const res = await saveContent(params);
    showMessage(res.message);
    edit.value = false;
  };
  const planOpe = async (ope) => {
    if (!record.value.plan) {
      showMessage('方案为空!');
      return;
    }
    openConfirmDrawer(true, {
      id: record.value.plan.id,
      quesId: record.value.id,
      ope,
      type: 'plan',
      ts: record.value.plan.ts,
      configName: 'quesLib_plan_confirm_form',
    });
  };

  const resOpe = async (ope) => {
    if (!record.value.res) {
      showMessage('结果为空!');
      return;
    }
    openConfirmDrawer(true, {
      id: record.value.res.id,
      quesId: record.value.id,
      ope,
      ts: record.value.res.ts,
      configName: 'quesLib_res_confirm_form',
    });
  };

  const toPlanView = () => {
    planRef.value.$el.scrollIntoView({
      behavior: 'smooth', // 平滑过渡
      block: 'start', // 上边框与视窗顶部平齐。默认值
    });
  };
  const toResView = () => {
    resRef.value.$el.scrollIntoView({
      behavior: 'smooth', // 平滑过渡
      block: 'start', // 上边框与视窗顶部平齐。默认值
    });
  };
  const loadInfoForm = async () => {
    const res = await queslibInfoForm({ id: route.query.quesId });
    record.value = res.queslibInfo;
    record.value.__t = new Date().getTime();
    showForm.value = record.value.isNewRecord;
    const configRes = await formSet({ viewCode: 'quesLib_input_form' });
    formConfig.value = configRes.layVoucherView.formConfig;
    const inputFormSchemas = formSchemas(
      configRes.layVoucherView.formTabs[0].colList,
      formConfig.value.formColNum,
      res.queslibInfo,
    ) as FormSchema[];
    inputFormSchemas.forEach((item) => {
      let obj = { ...item.componentProps };
      item.componentProps = ({ schema, formActionType, formModel }) => {
        return {
          ...obj,
          onChange: () => {
            debounceSave(schema, formActionType, formModel, obj);
          },
        };
      };
      item.itemProps = { validateTrigger: 'blur' };
      if (!record.value.isNewRecord) {
        item.dynamicDisabled = record.value.allowEdit || !record.value.created;
      }
    });
    await setProps({
      labelWidth: 120, // 控件前面的标签宽度
      schemas: inputFormSchemas, // 控件定义列表
      baseColProps: { lg: parseInt(formConfig.value.formColNum), md: 24 },
      fieldMapToTime: fieldMapToTime,
    });
    await setFieldsValue(record.value);
  };
  const loadPlanForm = async () => {
    // 方案===========
    record.value.plan.__t = new Date().getTime();
    const res = await formSet({ viewCode: 'quesLib_plan_form' });
    const inputFormSchemas2 = formSchemas(
      res.layVoucherView.formTabs[0].colList,
      res.layVoucherView.formConfig.formColNum,
      record.value.plan,
    ) as FormSchema[];
    inputFormSchemas2.forEach((item) => {
      if (item.slot == 'remarks') {
        item.ifShow = false;
      }
      item.dynamicDisabled = true;
    });

    await setProps2({
      labelWidth: 120, // 控件前面的标签宽度
      schemas: inputFormSchemas2, // 控件定义列表
      baseColProps: { lg: parseInt(res.layVoucherView.formConfig.formColNum), md: 24 },
    });
    await setFieldsValue2(record.value.plan);
  };

  const loadResForm = async () => {
    record.value.res.__t = new Date().getTime();
    const res = await formSet({ viewCode: 'quesLib_res_form' });
    const inputFormSchemas3 = formSchemas(
      res.layVoucherView.formTabs[0].colList,
      res.layVoucherView.formConfig.formColNum,
      record.value.res,
    ) as FormSchema[];
    inputFormSchemas3.forEach((item) => {
      if (item.slot == 'remarks') {
        item.ifShow = false;
      }
      item.dynamicDisabled = true;
    });
    await setProps3({
      labelWidth: 120, // 控件前面的标签宽度
      schemas: inputFormSchemas3, // 控件定义列表
      baseColProps: { lg: parseInt(res.layVoucherView.formConfig.formColNum), md: 24 },
    });
    await setFieldsValue3(record.value.res);
  };

  const deleteInfo = async () => {
    const res = await queslibInfoDelete({ id: record.value.id });
    showMessage(res.message);
    await closeCurrentTabPage();
  };
  const handlePlanSubmit = async () => {
    const data = {
      id: record.value.plan.id,
      ope: 2,
      quesId: record.value.id,
      ts: record.value.plan.ts,
    };
    const res = await queslibPlanConfirm(data);
    showMessage(res.message);
    await loadInfoForm();
    loadPlanForm();
  };
  const handleResSubmit = async () => {
    const data = {
      id: record.value.res.id,
      ope: 2,
      quesId: record.value.id,
      ts: record.value.res.ts,
    };
    const res = await queslibResConfirm(data);
    showMessage(res.message);
    await loadInfoForm();
    loadResForm();
  };

  const handleJoinPrj = () => {
    prjSelRef.value.openSelectModal();
    console.log(prjSelRef.value);
    prjSelRef.value.configRef = {
      treeProps: {
        title: '项目分类',
        api: plmPrjKindInfoListData,
      },
      treeTableFieldName: 'cmkindid',
    };
  };

  const prjSelect = async (data) => {
    if (data) {
      const formData = await getFieldsValue();
      const prjInfo = {
        defMap: {
          plm_prj_id: data[0].projectid,
          plm_prj_code: data[0].projectcode,
          plm_prj_name: data[0].projectname,
        },
      };
      await setFieldsValue({
        ...formData,
        ...prjInfo,
        dateRange: [
          (formData.beginDate != 'Invalid Date' && formData.beginDate) || '',
          (formData.endDate != 'Invalid Date' && formData.endDate) || '',
        ],
      });
      if (record.value.id) {
        let params = {
          id: record.value.id,
          isNewRecord: record.value.isNewRecord,
        };
        queslibInfoFieldSave(params, prjInfo).then(() => {
          loadInfoForm();
        });
      }
    }
  };
</script>

<style lang="less" scoped>
  .ant-timeline-item-tail {
    position: absolute;
    top: 10px;
    left: 4px;
    height: calc(100% - 10px);
    border-left: 2px solid #aaa;
  }
  .content {
    background-color: #eee;
    width: 100%;
    height: 100%;
  }
  .ui-container {
    background-color: #ffffff;
    width: 93%;
    // min-width: 1100px;
    min-height: 85vh;
    padding: 20px 20px;
    margin: 0 auto;
  }
  .tool {
    margin: 50px 50px;
    margin-top: 0;
    .btn {
      margin: 0 5px;
    }
  }
  .steptool {
    right: 80px;
    bottom: 160px;
    z-index: 999;
    margin-top: -60px;
    position: fixed;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-direction: column;
    flex-direction: column;
    -webkit-box-align: end;
    -ms-flex-align: end;
    align-items: flex-end;

    button {
      margin: 5px 0;
      span {
        font-size: 16px;
        font-weight: bolder;
        font-family: 'Microsoft YaHei';
      }
    }
  }
  .span-line {
    // margin: 30px 0;
    color: #1951be;
    font-size: 28px;
    height: 63px;
    padding: 10px 0;
    background-color: #c9c9c941;
    @img-w: 40px;
    img {
      width: @img-w;
      height: @img-w;
      margin-right: 10px;
    }
    span {
      line-height: @img-w;
    }
  }
  .plan-content,
  .res-content {
    padding: 10px 20px;
  }
  .ant-descriptions-title {
    font-size: 28px !important;
  }
  .ant-divider {
    margin-top: 2px;
    margin-bottom: 10px;
  }
</style>
